<template>
  <el-container class="meeting-container">
    <!-- 侧边栏 -->
    <el-aside class="sidebar">
      <el-menu :default-active="activeTab" class="menu" @select="handleSelect">
        <el-menu-item index="dashboard">
          <el-icon><Files /></el-icon>
          <router-link to="#" class="menu-link">我的进度</router-link>
        </el-menu-item>
        <el-menu-item index="submitTask">
          <el-icon><Upload /></el-icon>
          <router-link to="#" class="menu-link">提交任务</router-link>
        </el-menu-item>
        <el-menu-item index="teamTasks">
          <el-icon><Flag /></el-icon>
          <router-link to="#" class="menu-link">团队任务</router-link>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 右侧内容区 -->
    <el-main class="content">
      <!-- 我的进度模块 -->
      <div v-if="activeTab === 'dashboard'" class="module">
        <h2 class="module-title">我的任务状态</h2>
        <el-table :data="myTasks" stripe class="custom-table">
          <el-table-column prop="description" label="任务描述" />
          <el-table-column prop="status" label="任务状态" width="140">
            <template #default="{ row }">
              <el-tag :type="tagType(row.status)">
                {{ statusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <!-- 进度图表区域 -->
        <div id="progressChart" class="chart-area">
          <!-- 这里将用JS代码初始化图表 -->
        </div>
      </div>

      <!-- 提交任务模块 -->
      <div v-if="activeTab === 'submitTask'" class="module">
        <h2 class="module-title">提交任务</h2>
        <!-- 显示当前用户的任务列表 -->
        <el-table :data="myTasks" stripe class="custom-table">
          <el-table-column prop="description" label="任务描述" />
          <el-table-column prop="status" label="任务状态" width="140">
            <template #default="{ row }">
              <el-tag :type="tagType(row.status)">
                {{ statusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="openFileUploadModal(row)">提交文件</el-button>
              <el-button size="small" type="success" @click="openReviewModal(row)">查看评阅结果</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 团队任务模块 -->
      <div v-if="activeTab === 'teamTasks'" class="module">
        <h2 class="module-title">团队成员任务</h2>
        <el-table :data="groupedSubtasksList" stripe class="custom-table">
          <el-table-column prop="assigned_to" label="用户名" />
          <el-table-column prop="status" label="任务状态" width="140">
            <template #default="{ row }">
              <el-tag :type="tagType(row.status)">
                {{ statusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140">
            <template #default="{ row }">
              <el-button size="small" type="danger" @click="sendReminder(row)">发送提醒</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>

    <!-- 文件上传对话框（使用原生 input） -->
    <el-dialog title="任务文件提交" v-model ="fileUploadModalVisible" width="30%">
      <el-form :model="submitForm" label-width="120px">
        <el-form-item label="选择任务文件">
          <input type="file" accept=".txt,.pdf,.docx" @change="handleFileUpload" style="margin-bottom: 30px;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="fileUploadModalVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFile">提交文件</el-button>
      </template>
    </el-dialog>

    <!-- 评阅结果对话框 -->
    <el-dialog title="任务评阅结果" v-model ="reviewModalVisible">
      <div v-if="reviewResult">
        <p>{{ reviewResult }}</p>
      </div>
      <div v-else>
        <p>暂无评阅结果</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="reviewModalVisible = false">确定</el-button>
      </template>
    </el-dialog>
  </el-container>
</template>

<script>
import { defineComponent, ref, onMounted, nextTick } from 'vue';
import { ElDialog, ElForm, ElFormItem, ElButton } from 'element-plus';
import axios from '@/axiosInstance';
import { useRouter } from "vue-router";
import { Flag, Upload, Files } from "@element-plus/icons-vue";
import * as echarts from "echarts";
import * as pdfjsLib from 'pdfjs-dist/build/pdf';
import mammoth from "mammoth";

async function readTxtFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => resolve(e.target.result);
    reader.onerror = reject;
    reader.readAsText(file, "utf-8");
  });
}

async function parsePDF(file) {
  if (pdfjsLib.GlobalWorkerOptions.workerSrc === undefined) {
    pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.14.305/pdf.worker.min.js';
  }
  const arrayBuffer = await file.arrayBuffer();
  const typedArray = new Uint8Array(arrayBuffer);
  try {
    const pdf = await pdfjsLib.getDocument(typedArray).promise;
    let textContent = "";
    for (let i = 1; i <= pdf.numPages; i++) {
      const page = await pdf.getPage(i);
      const content = await page.getTextContent();
      const strings = content.items.map(item => item.str);
      textContent += strings.join(" ") + "\n";
    }
    return textContent;
  } catch (err) {
    throw new Error("PDF解析失败: " + err);
  }
}

async function parseDocx(file) {
  try {
    const arrayBuffer = await file.arrayBuffer();
    const result = await mammoth.extractRawText({ arrayBuffer });
    return result.value;
  } catch (err) {
    throw new Error("DOCX解析失败: " + err);
  }
}

export default defineComponent({
  name: "TeamDashboard",
  components: {
    Flag,
    Upload,
    Files,
    ElDialog,
    ElForm,
    ElFormItem,
    ElButton
  },
  setup() {
    const activeTab = ref('dashboard');
    const myTasks = ref([]);
    const groupedSubtasks = ref({});
    const groupedSubtasksList = ref([]);
    const submitForm = ref({ task_id: 0 });
    const parsedContent = ref('');
    const fileUploadModalVisible = ref(false);
    const reviewModalVisible = ref(false);
    const reviewResult = ref('');
    const selectedTask = ref(null);
    const uploadUrl = "http://39.105.217.183:8000/api/submit-task-file/";
    const groupId = ref(null);
    const router = useRouter();
    const taskId = ref(null);
    const sysUserId = ref(null);
    const users = ref(null);
    const sysusername = ref(null);

    onMounted(() => {
      const params = new URLSearchParams(window.location.search);
      taskId.value = params.get("taskId");
      sysUserId.value = params.get("sysUserId");
      groupId.value = params.get("groupId");
      sysusername.value = params.get("sysUserName");
      console.log("任务ID:", taskId.value, "用户ID:", sysUserId.value, "组ID:", groupId.value, "用户名:", sysusername.value);
      fetchSubtasks();
      fetchUsers();
      fetchMyTasks();
      // 如果需要初始化图表，可在此处调用 initChart();
    });

    const initChart = () => {
      console.log("初始化图表");
      const statusCounts = { on_time: 0, late: 0, in_progress: 0 };
      myTasks.value.forEach(task => {
        if (task.status in statusCounts) {
          statusCounts[task.status]++;
        }
      });
      const dataForChart = [
        { value: statusCounts.on_time, name: '按时完成' },
        { value: statusCounts.late, name: '超时提交' },
        { value: statusCounts.in_progress, name: '进行中' }
      ];
      const chartDom = document.getElementById('progressChart');
      if (!chartDom) return;
      const myChart = echarts.init(chartDom);
      const option = {
        title: { text: '任务进度分布', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: { orient: 'vertical', left: 'left', data: ['按时完成', '超时提交', '进行中'] },
        series: [{
          name: '任务状态',
          type: 'pie',
          radius: '50%',
          data: dataForChart,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      myChart.setOption(option);
    };

    const fetchSubtasks = async () => {
      try {
        if (!groupId.value) {
          console.error("groupId 未定义");
          return;
        }
        const response = await axios.get(`http://39.105.217.183:8000/api/subtasks/group/${groupId.value}/`);
        console.log("Fetched subtasks:", response.data);
        const data = response.data;
        const grouped = {};
        data.forEach((subtask) => {
          const dateKey = subtask.start_date;
          if (!grouped[dateKey]) {
            grouped[dateKey] = [];
          }
          grouped[dateKey].push(subtask);
        });
        groupedSubtasks.value = grouped;
        let list = [];
        Object.values(grouped).forEach(arr => {
          arr.forEach(item => list.push(item));
        });
        groupedSubtasksList.value = list;
      } catch (error) {
        console.error("Error fetching subtasks:", error.message || error);
      }
    };

    const fetchMyTasks = async () => {
      try {
        if (!groupId.value) {
          console.error("groupId 未定义");
          return;
        }
        const response = await axios.get(`http://39.105.217.183:8000/api/subtasks/group/${groupId.value}/`);
        console.log("Fetched subtasks:", response.data);
        const data = response.data;
        myTasks.value = [];
        data.forEach((subtask) => {
          if (subtask.assigned_to === sysusername.value) {
            myTasks.value.push(subtask);
          }
        });
        console.log("My subtasks:", myTasks.value);
      } catch (error) {
        console.error("Error fetching my tasks:", error.message || error);
      }
      nextTick(() => {
        initChart();
      });
    };

    const fetchUsers = async () => {
      try {
        const response = await axios.get("http://39.105.217.183:8000/api/all-users/");
        users.value = response.data;
      } catch (error) {
        console.error("Error fetching users:", error.message || error);
      }
    };

    const sendReminder = async (task) => {
      try {
        alert("已提醒：" + task.assigned_to);
        const response = await axios.post(`http://39.105.217.183:8000/api/task/remind/`, { task_id: task.id, user_id: sysUserId.value });
        console.log("提醒发送成功:", response.data);
      } catch (error) {
        console.error("发送提醒失败:", error);
      }
    };

    // 修改后的 handleFileUpload，统一支持 TXT, PDF, DOCX 文件
    const handleFileUpload = async (event) => {
      const file = event.target.files[0];
      if (!file) return;
      const extension = file.name.split('.').pop().toLowerCase();
      try {
        if (extension === "txt") {
          parsedContent.value = await readTxtFile(file);
        } else if (extension === "pdf") {
          parsedContent.value = await parsePDF(file);
        } else if (extension === "docx") {
          parsedContent.value = await parseDocx(file);
        } else {
          window.$message && window.$message.error("不支持的文件格式！");
          return;
        }
        console.log("文件解析成功：", parsedContent.value);
      } catch (error) {
        console.error("文件解析失败：", error);
        window.$message && window.$message.error("文件解析失败！");
      }
    };

    // 切换模块并更新 URL 参数
    const handleSelect = (index) => {
      activeTab.value = index;
      router.replace({
        query: {
          taskId: taskId.value,
          sysUserId: sysUserId.value,
          groupId: groupId.value,
          sysUserName: sysusername.value
        }
      });
      if (index === 'dashboard') {
        fetchMyTasks();
      } else if (index === 'teamTasks') {
        fetchSubtasks();
      }
    };

    const statusLabel = (status) => {
      if (status === 'on_time') return '按时完成';
      else if (status === 'late') return '超时提交';
      else if (status === 'pending') return '待完成';
      return status;
    };

    const tagType = (status) => {
      if (status === 'on_time') return 'success';
      else if (status === 'late') return 'danger';
      else if (status === 'pending') return 'warning';
      return 'info';
    };

    const openFileUploadModal = (task) => {
      selectedTask.value = task;
      submitForm.value.task_id = task.id;
      fileUploadModalVisible.value = true;
      console.log("打开文件上传对话框", fileUploadModalVisible.value);
    };

    const submitFile = async () => {
      try {
        const payload = {
          task_id: submitForm.value.task_id,
          fileContent: parsedContent.value,
          taskDescription: selectedTask.value.description,
          user_id: sysUserId.value
        };
        console.log("提交文件：", payload);
        const response = await axios.post(uploadUrl, payload);
        const updatedStatus = response.data.status;
        const task = myTasks.value.find(task => task.id == submitForm.value.task_id);
        if (task) {
          task.status = updatedStatus;
        }
        fileUploadModalVisible.value = false;
        parsedContent.value = '';
      } catch (error) {
        console.error("文件提交失败:", error);
      }
    };

    const openReviewModal = async (task) => {
      selectedTask.value = task;
      try {
        console.log("获取评阅结果：", task.id);
        const response = await axios.get(`http://39.105.217.183:8000/api/get-subtask-review/?task_id=${task.id}`);
        reviewResult.value = response.data;
        console.log("评阅结果：", reviewResult.value);
      } catch (error) {
        console.error("获取评阅结果失败:", error);
        reviewResult.value = "评阅结果获取失败，请稍后再试。";
      }
      reviewModalVisible.value = true;
    };

    return {
      activeTab,
      myTasks,
      groupedSubtasksList,
      parsedContent,
      uploadUrl,
      fileUploadModalVisible,
      reviewModalVisible,
      reviewResult,
      sendReminder,
      fetchSubtasks,
      fetchUsers,
      fetchMyTasks,
      handleFileUpload,
      handleSelect,
      openFileUploadModal,
      submitFile,
      openReviewModal,
      statusLabel,
      tagType,
      groupId,
      taskId,
      sysUserId,
      sysusername
    };
  }
});
</script>

<style scoped>
.meeting-container {
  display: flex;
  min-height: 100vh;
  width: 1000px;
  background-color: #f0f2f5;
  margin: 0 auto;
}

/* 侧边栏 */
.sidebar {
  width: 220px;
  background: #f5f5f5;
  padding-top: 20px;
  border-right: 1px solid #ebeef5;
}

/* El-Menu */
.menu {
  border-right: none;
}
.menu .el-menu-item {
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
}
.menu .el-menu-item.is-active {
  background-color: #e6e6e6;
}
.menu-link {
  color: #000;
}

/* 右侧内容区 */
.content {
  flex: 1;
  padding: 20px;
  background: #fff;
  overflow-y: auto;
  max-width: 1200px;
  margin: 0 auto;
}

/* 模块通用卡片 */
.card {
  width: 100%;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 表格样式 */
.custom-table {
  margin-top: 20px;
}

/* 按钮样式 */
.el-button {
  margin: 5px;
}

/* 图表区域样式 */
.chart-area {
  margin-top: 20px;
  padding: 20px;
  width: 100%;
  height: 400px;
  border: 1px dashed #ccc;
  text-align: center;
}

/* 预览TXT文件内容 */
.parsed-content {
  background: #f5f5f5;
  padding: 10px;
  border: 1px dashed #ccc;
  white-space: pre-wrap;
}

/* 响应式设置 */
@media (max-width: 768px) {
  .meeting-container {
    flex-direction: column;
    width: 100%;
  }
  .sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #ebeef5;
  }
  .content {
    padding: 10px;
    max-width: 100%;
    margin: 0 auto;
  }
}
</style>